#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sqlite3
import os
import sys
from rich.console import Console
from rich.table import Table
from datetime import datetime

console = Console()

def view_trade_records(limit=20, offset=0, product=None, direction=None, date=None):
    """
    查看交易记录
    
    参数:
    limit: 显示记录数量
    offset: 起始位置
    product: 按产品筛选
    direction: 按方向筛选
    date: 按日期筛选 (格式: YYYY-MM-DD)
    """
    try:
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 构建查询条件
        query = "SELECT * FROM trade_records WHERE 1=1"
        params = []
        
        if product:
            query += " AND product_name = ?"
            params.append(product)
        
        if direction:
            query += " AND direction = ?"
            params.append(direction)
        
        if date:
            query += " AND timestamp LIKE ?"
            params.append(f"{date}%")
        
        query += " ORDER BY timestamp DESC LIMIT ? OFFSET ?"
        params.extend([limit, offset])
        
        # 执行查询
        cursor.execute(query, params)
        records = cursor.fetchall()
        
        # 获取列名
        cursor.execute("PRAGMA table_info(trade_records)")
        columns = [col[1] for col in cursor.fetchall()]
        
        # 创建表格
        table = Table(title="交易记录")
        for col in columns:
            table.add_column(col)
        
        # 添加数据行
        for record in records:
            table.add_row(*[str(item) for item in record])
        
        console.print(table)
        
        # 显示记录总数
        cursor.execute("SELECT COUNT(*) FROM trade_records")
        total = cursor.fetchone()[0]
        console.print(f"共 {total} 条记录，当前显示 {len(records)} 条")
        
        conn.close()
        
    except Exception as e:
        console.print(f"查看交易记录时出错: {e}", style="red")

def delete_trade_record(record_id):
    """
    删除指定ID的交易记录
    """
    try:
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 先查询记录是否存在
        cursor.execute("SELECT * FROM trade_records WHERE id = ?", (record_id,))
        record = cursor.fetchone()
        
        if not record:
            console.print(f"未找到ID为 {record_id} 的记录", style="yellow")
            conn.close()
            return False
        
        # 删除记录
        cursor.execute("DELETE FROM trade_records WHERE id = ?", (record_id,))
        conn.commit()
        conn.close()
        
        console.print(f"成功删除ID为 {record_id} 的记录", style="green")
        return True
        
    except Exception as e:
        console.print(f"删除交易记录时出错: {e}", style="red")
        return False

def export_trade_records(filename=None, product=None, start_date=None, end_date=None):
    """
    导出交易记录到CSV文件
    """
    try:
        import csv
        from datetime import datetime
        
        conn = sqlite3.connect('trade_monitor.db')
        cursor = conn.cursor()
        
        # 构建查询条件
        query = "SELECT * FROM trade_records WHERE 1=1"
        params = []
        
        if product:
            query += " AND product_name = ?"
            params.append(product)
        
        if start_date:
            query += " AND timestamp >= ?"
            params.append(start_date)
        
        if end_date:
            query += " AND timestamp <= ?"
            params.append(end_date + " 23:59:59")
        
        query += " ORDER BY timestamp"
        
        # 执行查询
        cursor.execute(query, params)
        records = cursor.fetchall()
        
        # 获取列名
        cursor.execute("PRAGMA table_info(trade_records)")
        columns = [col[1] for col in cursor.fetchall()]
        
        # 如果未指定文件名，则使用当前日期时间
        if not filename:
            current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"trade_records_{current_time}.csv"
        
        # 写入CSV文件
        with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(columns)  # 写入表头
            writer.writerows(records)  # 写入数据
        
        console.print(f"成功导出 {len(records)} 条记录到文件: {filename}", style="green")
        conn.close()
        return True
        
    except Exception as e:
        console.print(f"导出交易记录时出错: {e}", style="red")
        return False

def show_help():
    """
    显示帮助信息
    """
    console.print("交易记录管理工具使用说明:", style="bold blue")
    console.print("1. 查看记录: python trade_records_manager.py view [--limit N] [--offset N] [--product CODE] [--direction DIR] [--date YYYY-MM-DD]")
    console.print("2. 删除记录: python trade_records_manager.py delete ID")
    console.print("3. 导出记录: python trade_records_manager.py export [--file FILENAME] [--product CODE] [--start YYYY-MM-DD] [--end YYYY-MM-DD]")
    console.print("4. 显示帮助: python trade_records_manager.py help")

if __name__ == "__main__":
    if len(sys.argv) < 2 or sys.argv[1] == "help":
        show_help()
    elif sys.argv[1] == "view":
        # 解析参数
        limit = 20
        offset = 0
        product = None
        direction = None
        date = None
        
        i = 2
        while i < len(sys.argv):
            if sys.argv[i] == "--limit" and i+1 < len(sys.argv):
                limit = int(sys.argv[i+1])
                i += 2
            elif sys.argv[i] == "--offset" and i+1 < len(sys.argv):
                offset = int(sys.argv[i+1])
                i += 2
            elif sys.argv[i] == "--product" and i+1 < len(sys.argv):
                product = sys.argv[i+1]
                i += 2
            elif sys.argv[i] == "--direction" and i+1 < len(sys.argv):
                direction = sys.argv[i+1]
                i += 2
            elif sys.argv[i] == "--date" and i+1 < len(sys.argv):
                date = sys.argv[i+1]
                i += 2
            else:
                i += 1
        
        view_trade_records(limit, offset, product, direction, date)
    
    elif sys.argv[1] == "delete" and len(sys.argv) > 2:
        delete_trade_record(int(sys.argv[2]))
    
    elif sys.argv[1] == "export":
        # 解析参数
        filename = None
        product = None
        start_date = None
        end_date = None
        
        i = 2
        while i < len(sys.argv):
            if sys.argv[i] == "--file" and i+1 < len(sys.argv):
                filename = sys.argv[i+1]
                i += 2
            elif sys.argv[i] == "--product" and i+1 < len(sys.argv):
                product = sys.argv[i+1]
                i += 2
            elif sys.argv[i] == "--start" and i+1 < len(sys.argv):
                start_date = sys.argv[i+1]
                i += 2
            elif sys.argv[i] == "--end" and i+1 < len(sys.argv):
                end_date = sys.argv[i+1]
                i += 2
            else:
                i += 1
        
        export_trade_records(filename, product, start_date, end_date)
    
    else:
        console.print("无效的命令，请使用 'help' 查看帮助", style="red")
        show_help()